package com.xteam.ecsystem.dao.Impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xteam.ecsystem.dao.IFrontCartDao;
import com.xteam.ecsystem.entities.BaseCartInfo;
import com.xteam.ecsystem.entities.BaseGoodsAttribute;
import com.xteam.ecsystem.entities.BaseGoodsInfo;
import com.xteam.ecsystem.entities.BaseTypeAttribute;
import com.xteam.ecsystem.utils.PageCenterStation;
import com.xteam.ecsystem.utils.StringUtil;

@Repository
@SuppressWarnings("unchecked")
/**
 * 
 * 前端购物车实现类
 * 
 * @author ls
 * 
 */
public class FrontCartDaoImpl extends DDLPrefix implements IFrontCartDao {
	
	@Autowired
	private BaseDaoImpl baseDao;

	@Override
	public PageCenterStation<?> getUserCartList(String userId, int pageIndex, int pageSize) {
		List list = new ArrayList();

		try {
			// 更新购物车信息
			baseDao.queryByProcedure("update_cart_info", new Object[] { userId });

			String hql = SQL_FROM + BaseCartInfo.REF + SQL_WHERE + "1=1";
			String countHQL = SQL_SELECT + "count(*) " + SQL_FROM + BaseCartInfo.REF + SQL_WHERE + "1=1";

			if (StringUtil.isNotNullOrEmpty(userId)) {
				hql += SQL_AND + "bciUser=?";
				countHQL += SQL_AND + "bciUser=?";
				list.add(userId);
			}

			hql += SQL_ORDERBY + "bciTime asc";

			PageCenterStation<?> p = (PageCenterStation<?>) this.baseDao.queryList(countHQL, hql, list
					.toArray(), pageIndex * pageSize, pageSize);

			return p;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void addToCart(String id, String attr, int num, String userId, int userRole) {
		List list = new ArrayList();
		String hql = "";
		String innerhql = "";
		if (attr == "") {
			hql = "select new " + BaseGoodsInfo.REF + " (bgi.bgiId,bgi.bgiName,bgi.bgiPrice,"
					+ "bgi.bgiMarket) from " + BaseGoodsInfo.REF
					+ " as bgi where bgi.bgiId = ? and bgi.bgiState = 1";
			list = this.baseDao.find(hql, new Object[] { id });
		} else {
			String attrIds[] = attr.split(",");
			for (int i = 0, len = attrIds.length; i < len; i++) {
				innerhql += "'" + attrIds[i] + "',";
			}
			innerhql = innerhql.substring(0, innerhql.length() - 1);
			hql = "select new "
					+ BaseGoodsInfo.REF
					+ " (bgi.bgiId,bgi.bgiName,bgi.bgiPrice,"
					+ " bgi.bgiMarket,bga.bgaId,bga.bgaPrice,bga.bgaValue,bta.btaName) from "
					+ BaseGoodsInfo.REF
					+ " as bgi, "
					+ BaseGoodsAttribute.REF
					+ " as bga, "
					+ BaseTypeAttribute.REF
					+ " as bta "
					+ " where bgi.bgiId = bga.bgaGoods and bta.btaId = bga.bgaTattri and bgi.bgiState = 1"
					+ " and bgi.bgiId = ? and bga.bgaId in (" + innerhql + ")";
			list = this.baseDao.find(hql, new Object[] { id });
		}
		if (list.size() > 0) {
			// 组装属性ID
			String bciattr = "";
			double attrprice = 0;
			String attrname = "";
			for (int i = 0, len = list.size(); i < len; i++) {
				BaseGoodsInfo bgi = new BaseGoodsInfo();
				bgi = (BaseGoodsInfo) list.get(i);
				bciattr += bgi.getBgaId() + ",";
				if (bgi.getBgaPrice() != null) {
					attrprice = attrprice + bgi.getBgaPrice();
					if (bgi.getBgaPrice() != 0) {
						attrname += bgi.getBtaName() + ":" + bgi.getBgaValue() + "["
								+ StringUtil.subZeroAndDot(bgi.getBgaPrice().toString()) + "]<br/>";
					} else {
						attrname += bgi.getBtaName() + ":" + bgi.getBgaValue() + "<br/>";
					}
				} else {
					if (bgi.getBtaName() != null && bgi.getBgaValue() != null) {
						attrname += bgi.getBtaName() + ":" + bgi.getBgaValue() + "<br/>";
					}
				}
			}
			bciattr = bciattr.substring(0, bciattr.length() - 1);
			BaseGoodsInfo bgi = new BaseGoodsInfo();
			bgi = (BaseGoodsInfo) list.get(0);

			// 根据商品ID，用户ID，属性ID查询购物车中是否已经存在该商品
			hql = "from " + BaseCartInfo.REF + " where bciUser = ? and bciAttrid = ? and bciGoods = ?";
			// 购物车表实体
			BaseCartInfo bci = (BaseCartInfo) this.baseDao.findObject(hql, new Object[] { userId,
					bciattr, bgi.getBgiId() });
			if (bci != null) {
				bci.setBciNumber(bci.getBciNumber() + num);
				bci.setBciTotal((bci.getBciPrice() + bci.getBciAttprice()) * bci.getBciNumber());
				bci.setBciTime(new java.util.Date());
				baseDao.update(bci);
			} else {
				bci = new BaseCartInfo();
				bci.setBciUser(userId);
				bci.setBciGoods(bgi.getBgiId());
				bci.setBciAttrid(bciattr);
				bci.setBciNumber(num);
				bci.setBciMarket(bgi.getBgiMarket() + attrprice);
				bci.setBciPrice(bgi.getBgiPrice() + attrprice);
				bci.setBciAttprice(attrprice);
				bci.setBciTotal(num * (bgi.getBgiPrice() + attrprice));
				bci.setBciName(bgi.getBgiName());
				bci.setBciPicurl("");
				bci.setBciAttrname(attrname);
				bci.setBciTime(new java.util.Date());
				bci.setBciRole(userRole);
				baseDao.save(bci);
			}
		}

	}

	/**
	 * 单个商品价格小计
	 */
	@Override
	public String getTotalPrice(String id, String attr, int num) {
		double totalPrice = 0.00;
		List list = new ArrayList();
		String sql = "";
		String innerSQL = "";
		if (attr == "") {
			sql = "SELECT bgi.bgi_price FROM base_goods_info AS bgi WHERE bgi.bgi_id = '" + id + "'";
			list = baseDao.queryListWithSql(sql);
			BigDecimal bdsp = (BigDecimal) (list.get(0));
			totalPrice = bdsp.doubleValue();
			totalPrice = totalPrice * num;
		} else {
			String attrIds[] = attr.split(",");
			for (int i = 0, len = attrIds.length; i < len; i++) {
				innerSQL += "'" + attrIds[i] + "',";
			}
			innerSQL = innerSQL.substring(0, innerSQL.length() - 1);
			sql = "SELECT bgi.bgi_price,SUM(bga.bga_price) AS bga_price "
					+ " FROM base_goods_info AS bgi,base_goods_attribute AS bga "
					+ " WHERE bgi.bgi_id = bga.bga_goods AND bgi.bgi_id = '" + id + "'"
					+ " AND bga.bga_id IN(" + innerSQL + "); ";
			list = baseDao.queryListWithSql(sql);
			// 商品价格
			BigDecimal bdsp = (BigDecimal) ((Object[]) list.get(0))[0];
			// 商品属性价格
			BigDecimal bdsx = (BigDecimal) ((Object[]) list.get(0))[1];
			totalPrice = bdsp.doubleValue() + bdsx.doubleValue();
			totalPrice = totalPrice * num;
		}
		return String.valueOf(totalPrice);
	}

	@Override
	public void dropFromCart(String bciId, String userId) {
		try {
			String hql = "";
			hql = "delete from " + BaseCartInfo.REF + " where bciId = ? and bciUser = ?";
			baseDao.executeUpdate(hql, new Object[] { bciId, userId });
		} catch (Exception e) {
		}
	}

	@Override
	public void clearCartByUserId(String userId) {
		try {
			String hql = "";
			hql = "delete from " + BaseCartInfo.REF + " where bciUser = ?";
			baseDao.executeUpdate(hql, new Object[] { userId });
		} catch (Exception e) {
		}

	}

	@Override
	public String updateCartGoods(String bciId, int num, String userId) {
		try {
			// 用于返还前台的商品总价
			double totalPrice = 0.00;
			String hql = "";
			hql = "from " + BaseCartInfo.REF + " where bciId = ? and bciUser = ?";

			BaseCartInfo bci = (BaseCartInfo) baseDao.findObject(hql, new Object[] { bciId, userId });

			if (bci != null) {
				bci.setBciNumber(num);
				totalPrice = (bci.getBciPrice() + bci.getBciAttprice()) * num;
				bci.setBciTotal(totalPrice);
				bci.setBciTime(new java.util.Date());
				baseDao.update(bci);
			}

			return String.valueOf(totalPrice);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 
	 * 获取购物车中商品总价
	 * 
	 * @see com.xteam.ecsystem.dao.IFrontCartDao#getCartTotal(java.lang.String)
	 */
	@Override
	public double getCartTotal(String userId) {
		double total = 0.00;
		if (userId != "") {
			String sql = "SELECT SUM(bci_total) as total FROM base_cart_info WHERE bci_user = ?";
			List list = baseDao.queryWithSQL(Map.class, sql, new Object[] { userId });
			BigDecimal bd = (BigDecimal) ((Map) list.get(0)).get("total");
			if (bd != null) {
				total = bd.doubleValue();
			}
			return total;
		} else {
			return 0;
		}
	}

	@Override
	public List<?> getAllGoodsByUser(String userId) {
		try {
			List list = baseDao.findAllByCriterions(BaseCartInfo.class, new Criterion[] {Restrictions.eq("bciUser", userId)});
			return list;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public int countCartGoods(String userId) {
		String hql = SQL_SELECT + "count(*)" + SQL_FROM + BaseCartInfo.REF + SQL_WHERE + " bciUser = ?";
		Long count = baseDao.count(hql, new Object[] { userId });
		return count.intValue();
	}
}
